package com.fowo.api.datainterface.service.impl.implCore;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.fowo.api.datainterface.aspect.BaseAspect;
import com.fowo.api.datainterface.constants.Constants;
import com.fowo.api.datainterface.constants.DataTypeKind;
import com.fowo.api.datainterface.constants.RequestMethodKind;
import com.fowo.api.datainterface.model.DataContextModel;
import com.fowo.api.datainterface.service.serviceCore.BaseInvokeService;
import com.fowo.api.datainterface.util.Common;
import com.fowo.api.datainterface.util.JScriptUtil;
import com.fowo.api.datainterface.util.JsonUtil;
import com.fowo.api.shein.util.ApiSignUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;

@Service
@Slf4j
@DS("ds24")
@RequiredArgsConstructor
public class SheinServiceImpl implements BaseInvokeService {

    private final Common common;

    private volatile BaseAspect baseAspect;

    private final JScriptUtil jScriptUtil;

    public synchronized BaseAspect getBaseAspect(String type) {
        return ObjUtil.isEmpty(baseAspect) ? new BaseAspect(type) : baseAspect;
    }

    @Override
    public DataTypeKind getType() {
        return DataTypeKind.SHEIN;
    }

    @Override
    public Object getAuth(DataContextModel.DatainterfaceAuthorityModel invoke) {
        return null;
    }

    @Override
    public Object invoke(DataContextModel.DatainterfaceInvokeModel invoke, Object currentParamsMap, JSONObject currentHeadersMap) {

        HttpHeaders header = new HttpHeaders();
        // 请求地址
        String path =  URLUtil.toUrlForHttp(StrUtil.concat(true,invoke.getAuthority().getRootPath(),invoke.getInterfaceUrl())).toString();
        // 请求方法
        HttpMethod requestMethod = common.convertRequestMethod(invoke.getRequestMethod());

        if (HttpUtil.isHttp(path) || HttpUtil.isHttps(path)) {
            if (!StrUtil.equalsIgnoreCase(RequestMethodKind.Post.getValue(), requestMethod.name()) &&
                    !StrUtil.equalsIgnoreCase(RequestMethodKind.Get.getValue(), requestMethod.name())) {
                Assert.isTrue(false, "接口 {} ，指定的查询类型 {} 错误 ！",  invoke.getEnCode(), requestMethod.name());
            }

            //请求头参数
            String openKeyId = currentHeadersMap.getString("openKeyId");
            String secretKey = currentHeadersMap.getString("secretKey");
            String timestamp = String.valueOf(new Date().getTime());
            String signature = ApiSignUtil.getSign(openKeyId,invoke.getInterfaceUrl(),secretKey,timestamp);

            header.set("Content-Type", "application/json;charset=UTF-8");
            header.set("x-lt-openKeyId", openKeyId);
            header.set("x-lt-timestamp", timestamp);
            header.set("x-lt-signature", signature);

            Object res;
            try {
                res = getBaseAspect(invoke.getAuthority().getAppName()).httpRequest(path, requestMethod, currentParamsMap, header,String.class, Constants.Read,StrUtil.EMPTY);
            } catch (Exception ex) {
                throw new RuntimeException(StrUtil.format("API 接口 {} ，执行 {} 操作 {} 发生异常 ",  invoke.getEnCode(), path, StrUtil.subPre(JsonUtil.getObjectToString(currentParamsMap), 500), ExceptionUtil.getRootCauseMessage(ex)));
            }
            if (ObjectUtil.isEmpty(res)) {
                throw new RuntimeException(StrUtil.concat(true, "拉取失败或无返回值：", StrUtil.subPre(JsonUtil.getObjectToString(res), 500)));
            }
            return jScriptUtil.callJsInvoke(invoke.getDataProcessing(), res == null ? new ArrayList<>() : res, null, null);
        } else {
            Assert.isTrue(false, "接口 {} ，地址 {} 错误 ！", invoke.getEnCode(), path);
        }
        return null;
    }
}
